// 返回一个最大值的数组
Array.prototype.max = function() {
	return Math.max.apply(null, this);
}

//返回一个最小值
Array.prototype.min = function() {
	return Math.min.apply(null, this);
}

// 计算数组平均数
Array.prototype.mean = function() {
	let sum = 0;
	for(let i = 0; i < this.length; i++) {
		sum += this[i];
	}
	return sum / this.length;
}

// 返回一个长度为n的数组,且每一个元素都被赋值成undefined
// Array.prototype.rep = function(n) {
// 	return Array.apply(null, new Array(n)).map(Number.prototype.valueOf, this[0]);
// }

Array.prototype.pip = function(x, y) {
	let c = false;
	for(let i = 0, j = this.length - 1; i < this.length; j = i++) {
		if(((this[i][1] > y) !== (this[j][1] > y)) &&
			(x < (this[j][0] - this[i][0]) * (y - this[i][1]) / (this[j][1] - this[i][1]) + this[i][0])) {
			c = !c;
		}
	}
	return c;
}

export default class Kriging {
	// static instance;
	
	constructor() {
		if (Kriging.instance) {
			return Kriging.instance;
		}
		Kriging.instance = this;
	}
	createArrayWithValues(value, n) {
        var array = [];
        for ( var i = 0; i < n; i++) {
            array.push(value);
        }
        return array;
    };
	// Matrix algebra矩阵代数
	matrix_diag(c, n) {
		// 新建一个n*n的矩阵
		let Z = this.createArrayWithValues(0, n * n);

		// 循环赋值c给Z矩阵的每一元素
		for (let i = 0; i < n; i++)
			Z[i * n + i] = c;
		return Z;
	}

	//将这个矩阵变为转置阵,也就是将元素颠倒顺序
	matrix_transpose(X, n, m) {
		let i, j, Z = Array(m * n);
		for (i = 0; i < n; i++)
			for (j = 0; j < m; j++)
				Z[j * n + i] = X[i * m + j];
		return Z;
	}

	// 再次改变数值,把c给每一个二维元素赋值
	matrix_scale(X, c, n, m) {
		for (let i = 0; i < n; i++)
			for (let j = 0; j < m; j++)
				X[i * m + j] *= c;
	}

	// 添加的方法
	matrix_add(X, Y, n, m) {
		//新建一个m*n的矩阵Z
		let Z = Array(n * m);
		for (let i = 0; i < n; i++)
			for (let j = 0; j < m; j++)
				//将X和Y矩阵相加合并成一个矩阵
				Z[i * m + j] = X[i * m + j] + Y[i * m + j];
		//返回一个Z矩阵
		return Z;
	};

	// 简单的矩阵乘法,矩阵和矩阵的乘法
	// 也就是前一个矩阵中的行乘以后一个矩阵中的列
	matrix_multiply(X, Y, n, m, p) {
		const Z = Array(n * p);
		for (let i = 0; i < n; i++) {
			for (let j = 0; j < p; j++) {
				Z[i * p + j] = 0;
				for (let k = 0; k < m; k++)
					Z[i * p + j] += X[i * m + k] * Y[k * p + j];
			}
		}
		return Z;
	};

	// 柯列斯基分解,这是一种将正定矩阵分解为上三角矩阵和下三角矩阵的方法,
	// 在优化矩阵计算的时候会用到的一种技巧
	// 也就是,下面左边为下三角,右边为上三角
	//100000 123456
	//120000 023456
	//123000 003456
	//123400 000456
	//123450 000056
	//123456 000006
	matrix_chol(X, n) {
		const p = Array(n);
		for (let i = 0; i < n; i++) {
			p[i] = X[i * n + i];
		}

		for (let i = 0; i < n; i++) {
			for (let j = 0; j < i; j++) {
				p[i] -= X[i * n + j] * X[i * n + j];
			}

			if (p[i] <= 0) {
				return false;
			}

			p[i] = Math.sqrt(p[i]);
			for (let j = i + 1; j < n; j++) {
				for (let k = 0; k < i; k++) {
					X[j * n + i] -= X[j * n + k] * X[i * n + k];
				}
				X[j * n + i] /= p[i];
			}
		}

		for (let i = 0; i < n; i++) {
			X[i * n + i] = p[i];
		}

		return true;
	};

	// 用斯基分解求矩阵的逆
	matrix_chol2inv(X, n) {
		let i, j, k, sum;
		for (i = 0; i < n; i++) {
			X[i * n + i] = 1 / X[i * n + i];
			for (j = i + 1; j < n; j++) {
				sum = 0;
				for (k = i; k < j; k++)
					sum -= X[j * n + k] * X[k * n + i];
				X[j * n + i] = sum / X[j * n + j];
			}
		}
		for (i = 0; i < n; i++)
			for (j = i + 1; j < n; j++)
				X[i * n + j] = 0;
		for (i = 0; i < n; i++) {
			X[i * n + i] *= X[i * n + i];
			for (k = i + 1; k < n; k++)
				X[i * n + i] += X[k * n + i] * X[k * n + i];
			for (j = i + 1; j < n; j++)
				for (k = j; k < n; k++)
					X[i * n + j] += X[k * n + i] * X[k * n + j];
		}
		for (i = 0; i < n; i++)
			for (j = 0; j < i; j++)
				X[i * n + j] = X[j * n + i];
	};

	// 用高斯-约当消去法求逆,它的速度不是最快的,但是它非常稳定
	// 如果A是求解矩阵,那么求A的逆矩阵则为
	// 用A矩阵右边乘以单位矩阵I（与A同行同列值为1的单位矩阵）
	// 公式为A*I=I*B,(等号右边要同时变化),也就是一个矩阵右边乘以单位矩阵化为,
	// 左边单位矩阵乘以B,则B就是A矩阵的逆
	matrix_solve(X, n) {
		const m = n;
		const b = Array(n * n);
		const indxc = Array(n);
		const indxr = Array(n);
		const ipiv = Array(n);
		let i, icol, irow, j, k, l, ll;
		let big, dum, pivinv, temp;

		for (i = 0; i < n; i++)
			for (j = 0; j < n; j++) {
				if (i === j) b[i * n + j] = 1;
				else b[i * n + j] = 0;
			}
		for (j = 0; j < n; j++) ipiv[j] = 0;
		for (i = 0; i < n; i++) {
			big = 0;
			for (j = 0; j < n; j++) {
				if (ipiv[j] !== 1) {
					for (k = 0; k < n; k++) {
						if (ipiv[k] === 0) {
							if (Math.abs(X[j * n + k]) >= big) {
								big = Math.abs(X[j * n + k]);
								irow = j;
								icol = k;
							}
						}
					}
				}
			}
			++(ipiv[icol]);

			if (irow !== icol) {
				for (l = 0; l < n; l++) {
					temp = X[irow * n + l];
					X[irow * n + l] = X[icol * n + l];
					X[icol * n + l] = temp;
				}
				for (l = 0; l < m; l++) {
					temp = b[irow * n + l];
					b[irow * n + l] = b[icol * n + l];
					b[icol * n + l] = temp;
				}
			}
			indxr[i] = irow;
			indxc[i] = icol;

			if (X[icol * n + icol] === 0) return false; // Singular

			pivinv = 1 / X[icol * n + icol];
			X[icol * n + icol] = 1;
			for (l = 0; l < n; l++) X[icol * n + l] *= pivinv;
			for (l = 0; l < m; l++) b[icol * n + l] *= pivinv;

			for (ll = 0; ll < n; ll++) {
				if (ll !== icol) {
					dum = X[ll * n + icol];
					X[ll * n + icol] = 0;
					for (l = 0; l < n; l++) X[ll * n + l] -= X[icol * n + l] * dum;
					for (l = 0; l < m; l++) b[ll * n + l] -= b[icol * n + l] * dum;
				}
			}
		}
		for (l = (n - 1); l >= 0; l--)
			if (indxr[l] !== indxc[l]) {
				for (k = 0; k < n; k++) {
					temp = X[k * n + indxr[l]];
					X[k * n + indxr[l]] = X[k * n + indxc[l]];
					X[k * n + indxc[l]] = temp;
				}
			}

		return true;
	}

	// 变差函数模型: 高斯
	Gaussian(h, nugget, range, sill, A) {
		return nugget + ((sill - nugget) / range) *
			(1.0 - Math.exp(-(1.0 / A) * Math.pow(h / range, 2)));
	};

	// 变差函数模型: 指数
	Exponential(h, nugget, range, sill, A) {
		return nugget + ((sill - nugget) / range) *
			(1.0 - Math.exp(-(1.0 / A) * (h / range)));
	};
	// 变差函数模型: 球形
	Spherical(h, nugget, range, sill, A) {
		if (h > range) return nugget + (sill - nugget) / range;
		return nugget + ((sill - nugget) / range) *
			(1.5 * (h / range) - 0.5 * Math.pow(h / range, 3));
	};

	//训练使用高斯过程与贝叶斯先验
	//使用gaussian、exponential或spherical模型对数据集进行训练,返回的是一个variogram对象；
	train(t, x, y, model, sigma2, alpha) {
		const variogram = {
			t: t,
			x: x,
			y: y,
			nugget: 0.0,
			range: 0.0,
			sill: 0.0,
			A: 1 / 3,
			n: 0
		};

		switch (model) {
			case "gaussian":
				variogram.model = this.Gaussian;
				break;
			case "exponential":
				variogram.model = this.Exponential;
				break;
			case "spherical":
				variogram.model = this.Spherical;
				break;
		}

		// 滞后距离/半方差
		let i, j, k, l, n = t.length;
		const distance = Array((n * n - n) / 2);
		for (i = 0, k = 0; i < n; i++)
			for (j = 0; j < i; j++, k++) {
				distance[k] = Array(2);
				distance[k][0] = Math.pow(
					Math.pow(x[i] - x[j], 2) +
					Math.pow(y[i] - y[j], 2), 0.5);
				distance[k][1] = Math.abs(t[i] - t[j]);
			}
		distance.sort(function (a, b) {
			return a[0] - b[0];
		});
		variogram.range = distance[(n * n - n) / 2 - 1][0];

		// Bin lag distance
		//本滞后距离
		const lags = ((n * n - n) / 2) > 30 ? 30 : (n * n - n) / 2;
		const tolerance = variogram.range / lags;
		var lag = this.createArrayWithValues(0,lags);
	var semi = this.createArrayWithValues(0,lags);
		if (lags < 30) {
			for (l = 0; l < lags; l++) {
				lag[l] = distance[l][0];
				semi[l] = distance[l][1];
			}
		} else {
			for (i = 0, j = 0, k = 0, l = 0; i < lags && j < ((n * n - n) / 2); i++, k = 0) {
				while (distance[j][0] <= ((i + 1) * tolerance)) {
					lag[l] += distance[j][0];
					semi[l] += distance[j][1];
					j++;
					k++;
					if (j >= ((n * n - n) / 2)) break;
				}
				if (k > 0) {
					lag[l] /= k;
					semi[l] /= k;
					l++;
				}
			}
			// 错误:分数不够
			if (l < 2) return variogram;
		}

		// 功能转换
		n = l;
		variogram.range = lag[n - 1] - lag[0];
		var X = this.createArrayWithValues(1,2 * n);
		const Y = Array(n);
		const A = variogram.A;
		for (i = 0; i < n; i++) {
			switch (model) {
				case "gaussian":
					X[i * 2 + 1] = 1.0 - Math.exp(-(1.0 / A) * Math.pow(lag[i] / variogram.range, 2));
					break;
				case "exponential":
					X[i * 2 + 1] = 1.0 - Math.exp(-(1.0 / A) * lag[i] / variogram.range);
					break;
				case "spherical":
					X[i * 2 + 1] = 1.5 * (lag[i] / variogram.range) -
						0.5 * Math.pow(lag[i] / variogram.range, 3);
					break;
			}
			Y[i] = semi[i];
		}

		// Least squares最小平方
		const Xt = this.matrix_transpose(X, n, 2);
		let Z = this.matrix_multiply(Xt, X, 2, n, 2);
		Z = this.matrix_add(Z, this.matrix_diag(1 / alpha, 2), 2, 2);
		const cloneZ = Z.slice(0);
		if (this.matrix_chol(Z, 2))
			this.matrix_chol2inv(Z, 2);
		else {
			this.matrix_solve(cloneZ, 2);
			Z = cloneZ;
		}
		const W = this.matrix_multiply(this.matrix_multiply(Z, Xt, 2, 2, n), Y, 2, n, 1);

		// Variogram parameters变差函数参数
		variogram.nugget = W[0];
		variogram.sill = W[1] * variogram.range + variogram.nugget;
		variogram.n = x.length;

		// Gram matrix with prior有先验Gram矩阵
		n = x.length;
		let K = Array(n * n);
		for (i = 0; i < n; i++) {
			for (j = 0; j < i; j++) {
				K[i * n + j] = variogram.model(Math.pow(Math.pow(x[i] - x[j], 2) +
					Math.pow(y[i] - y[j], 2), 0.5),
					variogram.nugget,
					variogram.range,
					variogram.sill,
					variogram.A);
				K[j * n + i] = K[i * n + j];
			}
			K[i * n + i] = variogram.model(0, variogram.nugget,
				variogram.range,
				variogram.sill,
				variogram.A);
		}

		// Inverse penalized Gram matrix projected to target vector
		//反向,,克矩阵投影到目标向量
		let C = this.matrix_add(K, this.matrix_diag(sigma2, n), n, n);
		const cloneC = C.slice(0);
		if (this.matrix_chol(C, n))
			this.matrix_chol2inv(C, n);
		else {
			this.matrix_solve(cloneC, n);
			C = cloneC;
		}

		// Copy unprojected inverted matrix as K
		//复制未投影的逆矩阵为K
		K = C.slice(0);
		const M = this.matrix_multiply(C, t, n, n, 1);
		variogram.K = K;
		variogram.M = M;

		return variogram;
	};

	// 模型预测,预测新的坐标点p=(xnew,ynew)的新的值（如高度,温度等）
	predict(x, y, variogram) {
		let i, k = Array(variogram.n);
		for (i = 0; i < variogram.n; i++)
			k[i] = variogram.model(Math.pow(Math.pow(x - variogram.x[i], 2) +
				Math.pow(y - variogram.y[i], 2), 0.5),
				variogram.nugget, variogram.range,
				variogram.sill, variogram.A);
		return this.matrix_multiply(k, variogram.M, 1, variogram.n, 1)[0];
	};
	// 模型方差
	variance(x, y, variogram) {
		let i, k = Array(variogram.n);
		for (i = 0; i < variogram.n; i++)
			k[i] = variogram.model(Math.pow(Math.pow(x - variogram.x[i], 2) +
				Math.pow(y - variogram.y[i], 2), 0.5),
				variogram.nugget, variogram.range,
				variogram.sill, variogram.A);
		return variogram.model(0, variogram.nugget, variogram.range,
			variogram.sill, variogram.A) +
			this.matrix_multiply(this.matrix_multiply(k, variogram.K,
				1, variogram.n, variogram.n),
				k, 1, variogram.n, 1)[0];
	};

	// 网格矩阵或轮廓路径
	// 使用刚才的variogram对象使polygons描述的地理位置内的格网元素具备不一样的预测值；
	// 使用一个边界区域按间距生成grid格网数据数组
	// polygons: 为区域的坐标数组,可以为多个polygon
	// variogram: 为第一步train产生的结果
	// width: 为生成grid格网的间距
	grid(polygons, variogram, width) {
		let i, j, k, n = polygons.length;
		if (n === 0) return;

		// Boundaries of polygons space
		//多边形空间的边界
		const xlim = [polygons[0][0][0], polygons[0][0][0]];
		const ylim = [polygons[0][0][1], polygons[0][0][1]];
		for (i = 0; i < n; i++) // Polygons多边形
			for (j = 0; j < polygons[i].length; j++) { // Vertices
				if (polygons[i][j][0] < xlim[0])
					xlim[0] = polygons[i][j][0];
				if (polygons[i][j][0] > xlim[1])
					xlim[1] = polygons[i][j][0];
				if (polygons[i][j][1] < ylim[0])
					ylim[0] = polygons[i][j][1];
				if (polygons[i][j][1] > ylim[1])
					ylim[1] = polygons[i][j][1];
			}

		// Alloc for O(n^2) space
		let xtarget, ytarget;
		const a = Array(2), b = Array(2);
		const lxlim = Array(2); // Local dimensions
		const lylim = Array(2); // Local dimensions
		const x = Math.ceil((xlim[1] - xlim[0]) / width);
		const y = Math.ceil((ylim[1] - ylim[0]) / width);

		const A = Array(x + 1);
		for (i = 0; i <= x; i++) A[i] = Array(y + 1);
		for (i = 0; i < n; i++) {
			// Range for polygons[i]
			lxlim[0] = polygons[i][0][0];
			lxlim[1] = lxlim[0];
			lylim[0] = polygons[i][0][1];
			lylim[1] = lylim[0];
			for (j = 1; j < polygons[i].length; j++) { // Vertices
				if (polygons[i][j][0] < lxlim[0])
					lxlim[0] = polygons[i][j][0];
				if (polygons[i][j][0] > lxlim[1])
					lxlim[1] = polygons[i][j][0];
				if (polygons[i][j][1] < lylim[0])
					lylim[0] = polygons[i][j][1];
				if (polygons[i][j][1] > lylim[1])
					lylim[1] = polygons[i][j][1];
			}

			// Loop through polygon subspace
			a[0] = Math.floor(((lxlim[0] - ((lxlim[0] - xlim[0]) % width)) - xlim[0]) / width);
			a[1] = Math.ceil(((lxlim[1] - ((lxlim[1] - xlim[1]) % width)) - xlim[0]) / width);
			b[0] = Math.floor(((lylim[0] - ((lylim[0] - ylim[0]) % width)) - ylim[0]) / width);
			b[1] = Math.ceil(((lylim[1] - ((lylim[1] - ylim[1]) % width)) - ylim[0]) / width);
			for (j = a[0]; j <= a[1]; j++)
				for (k = b[0]; k <= b[1]; k++) {
					xtarget = xlim[0] + j * width;
					ytarget = ylim[0] + k * width;
					if (polygons[i].pip(xtarget, ytarget))
						A[j][k] = this.predict(xtarget,
							ytarget,
							variogram);
				}
		}
		A.xlim = xlim;
		A.ylim = ylim;
		A.zlim = [variogram.t.min(), variogram.t.max()];
		A.width = width;
		return A;
	};

	contour(value, polygons, variogram) {

	}

	// 将得到的格网grid渲染至canvas上
	plot(canvas, grid, xlim, ylim, colors) {
		const ctx = canvas.getContext("2d");
		ctx.clearRect(0, 0, canvas.width, canvas.height);

		const range = [xlim[1] - xlim[0], ylim[1] - ylim[0], grid.zlim[1] - grid.zlim[0]];
		let i, j, x, y, z;
		const n = grid.length;
		const m = grid[0].length;
		const wx = Math.ceil(grid.width * canvas.width / (xlim[1] - xlim[0]));
		const wy = Math.ceil(grid.width * canvas.height / (ylim[1] - ylim[0]));
		for (i = 0; i < n; i++)
			for (j = 0; j < m; j++) {
				if (grid[i][j] === undefined) continue;
				x = canvas.width * (i * grid.width + grid.xlim[0] - xlim[0]) / range[0];
				y = canvas.height * (1 - (j * grid.width + grid.ylim[0] - ylim[0]) / range[1]);
				z = (grid[i][j] - grid.zlim[0]) / range[2];
				if (z < 0.0) z = 0.0;
				if (z > 1.0) z = 1.0;

				ctx.fillStyle = colors[Math.floor((colors.length - 1) * z)];
				ctx.fillRect(Math.round(x - wx / 2), Math.round(y - wy / 2), wx, wy);
			}
	}
}
